//
//  ZWParseLyricTool.m
//  08.音乐播放器
//
//  Created by mac on 16/3/15.
//  Copyright © 2016年 itheima. All rights reserved.
//

#import "ZWParseLyricTool.h"
#import "ZWLyricModel.h"

@implementation ZWParseLyricTool

+ (NSArray *)parseWithFileName:(NSString *)fileName{

    //1.获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    
    //2.转成字符串  一整串大字符串
    NSString *lyricContent = [NSString stringWithContentsOfURL:[NSURL fileURLWithPath:path] encoding:NSUTF8StringEncoding error:nil];
    
    //3.根据换行符   截取成一行行的字符串:[01:32.74][01:58.87]So I won't hesitate no more
    NSArray *linesArray = [lyricContent componentsSeparatedByString:@"\n"];
    
//    NSLog(@"%@",lyricContent);
    
    //正则表达式
    //pattern
    NSString *pattern = @"\\[[0-9][0-9]:[0-9][0-9].[0-9][0-9]\\]";
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
    //保存模型的数组
    NSMutableArray *mArray = [NSMutableArray array];
    //4.遍历数组
    for (NSString *line in linesArray) {
        
//        NSLog(@"%@",line);
        //与line进行匹配
        NSArray *matcheArray = [regular matchesInString:line options:0 range:NSMakeRange(0, line.length)];
        //拿出最后一个
        NSTextCheckingResult *result = matcheArray.lastObject;
        //截取文本部分
        NSString *textResult = [line substringFromIndex:result.range.location + result.range.length];
//        NSLog(@"%@",textResult);
        
        //时间
        for (NSTextCheckingResult *result in matcheArray) {
            NSString *timeString = [line substringWithRange:result.range];
//            NSLog(@"%@",timeString);
            //时间格式化
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"[mm:ss.SS]";
            NSDate *date = [formatter dateFromString:timeString];
            NSDate *zeroDate = [formatter dateFromString:@"[00:00.00]"];
            
            //歌词时间间隔
            NSTimeInterval time = [date timeIntervalSinceDate:zeroDate];
            
            //赋值给模型
            ZWLyricModel *lyricModel = [[ZWLyricModel alloc]init];
            lyricModel.time = time;
            lyricModel.lyricString = textResult;
            [mArray addObject:lyricModel];
        }
    }
    //按照时间排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:YES];
    return [mArray sortedArrayUsingDescriptors:@[sort]];
}

@end
